const Router = require('koa-router')
const router = new Router()
const bcrypt = require('bcryptjs')
const passport = require('koa-passport')
const jwt = require('jsonwebtoken')
const keys = require('../config/port')
const User = require("../models/userModel");


const validatorRegisterInput = require('../validation/register')
const validatorLoginInput = require('../validation/login')

/*
*@router POST  api/user/register
@desc 注册接口地址
@access  接口是公开的
*/
//api接口,处理注册用户的请求
router.post('/register', async ctx => {
  const { errors, isValid } = validatorRegisterInput(ctx.request.body)
    // 判断是否验证通过
    if(!isValid) {
      ctx.code = 400;
      ctx.body = errors;
      return;
    }
    const findResult = await User.find({name: ctx.request.body.name})
    if (findResult.length) {
        ctx.body = {
            message: '用户已存在,注册失败!',
            code: 400
        }
    } else {
        const newUser = new User({
            name: ctx.request.body.name,
            password: ctx.request.body.password
        });
        // 加密
        newUser.password = bcrypt.hashSync(newUser.password, bcrypt.genSaltSync(10));
        await newUser.save()
        .then(user => {
            ctx.body = {
                code: 200,
                // data: user
                message: 'OK',
                data: {}
            }
        }).catch(err => {
        console.log(err);
        })
    }
    
})


/*
*@router POST  api/user/login
@desc 登录接口地址 返回token
@access  接口是公开的
*/
router.post('/login', async ctx => {
    const { errors, isValid } = validatorLoginInput(ctx.request.body)
    // 判断是否验证通过
    if(!isValid) {
      ctx.code = 400;
      ctx.body = errors;
      return;
    }
    // 查询
    const findResult =  await User.find({name: ctx.request.body.name});
    const user = findResult[0]
    const password = ctx.request.body.password
    // 判断查没查到
    if(findResult.length == 0) {
      ctx.body = { code: 404, message:'用户不存在'} 
    } else {
      // 查到后验证密码
      const result = bcrypt.compareSync(password, user.password); // true
      // 验证通过
      if(result) {
        // 返回token
        const payload = {
          id: user.id,
          name: user.name,
          permission: user.permission
        }
        const token = jwt.sign(payload, keys.secretOrKey, {expiresIn: 86400})
        ctx.body = {code: 200, success: true, token: "Bearer " + token,permission: user.permission}
      }else{
       ctx.body = {
         code: 404,
         message: '密码错误'
       }
      }
    }
})


/*
*@router PUT  api/user/editpwd
@desc 修改密码接口
@access  接口是私有的
*/
router.put('/editpwd', passport.authenticate('jwt', { session: false }), async ctx => {
  console.log('ctx.request.body', ctx.request.body);
  console.log(' ctx.state.user',  ctx.state.user);
  let password = ctx.request.body.password
  const salt = bcrypt.genSaltSync(10);
  const hash = bcrypt.hashSync(password, salt);
  password = hash
  
  const updateResult = await User.updateOne(
    {_id: ctx.state.user.id},
    {$set: {password}},
    { runValidators: true}
  )
  if(updateResult.acknowledged) {
    ctx.body = {
      status: 200,
      msg:'密码更新成功'
    }
  } else {
    ctx.body = {
      status: 500,
      msg:'更新失败'
    }
  }
})
 
module.exports = router.routes();
